//
//  FriendCricleVC.swift
//  jiahui
//
//  Created by 3tee on 2024/12/12.
//

import UIKit
import SnapKit
import RxSwift
class FriendCricleVC: UIViewController {

    fileprivate let cellid = "friendcell"
    var cricleModels = [FriendCricleModel]()
    let vm = FriendCircleVM()
    
    lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRectZero, style: .plain)
        tab.delegate = self
        tab.dataSource = self
        
        tab.register(FriendCricleCell.self, forCellReuseIdentifier: cellid)
        return tab
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.top.equalTo(0)
        }
        
        cricleModels = vm.mockData()
        tableView.reloadData()
        // Do any additional setup after loading the view.
    }

}

extension FriendCricleVC: UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cricleModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: cellid) as! FriendCricleCell
        var model = cricleModels[indexPath.row]
        cell.model = model
        cell.openBtn.addTarget(self, action: #selector(clicked(_:)), for: .touchUpInside)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = cricleModels[indexPath.row]
        return model.cellHeight ?? 200
    }
    
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    @objc func clicked(_ btn: UIButton) {
        btn.isSelected = !btn.isSelected
        let cell = btn.superview?.superview as? FriendCricleCell
        let index = tableView.indexPath(for: cell! )
        print("当前点击的index = \(index?.row) ")
        if let idx = index?.row {
            let model = cricleModels[idx]
            model.isOpen = btn.isSelected
        }
        vm.reloadModels()
        cricleModels.forEach { m in
            print("当前文本是否展开 = \(m.isOpen)")
        }
        tableView.reloadData()
        
        //tableView.reloadData()
    }
    

    
}
